import { DirectiveBinding } from 'vue';

interface ElType extends HTMLElement {
  clickOutsideEvent: (event: Event) => void;
}

const clickOutside = {
  beforeMount(el: ElType, binding: DirectiveBinding) {
    el.clickOutsideEvent = function (event: Event) {
      // 检查点击是否发生在元素外部
      if (!(el === event.target || el.contains(event.target as Node))) {
        // 调用绑定的方法
        binding.value(event);
      }
    };
    // 使用setTimeout延迟绑定事件，避免与触发弹框的点击事件冲突
    setTimeout(() => {
      document.addEventListener('click', el.clickOutsideEvent);
    }, 10);
  },
  unmounted(el: ElType) {
    document.removeEventListener('click', el.clickOutsideEvent);
  }
};

export default clickOutside;
